﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RSPJ.Struct;

namespace RSPJ.Function
{
    public static class funcColorspace
    {
        public static HSI RGB2HSI(RGB rgb)
        {
            HSI hsi = new HSI();

            double r = (rgb.Red / 255.0);
            double g = (rgb.Green / 255.0);
            double b = (rgb.Blue / 255.0);

            if (r > b && g <= b)
            {
                hsi.Intensity = (r + g + b) / 3;
                hsi.Hue = (g - b) / (3 * (hsi.Intensity - b));
                hsi.Saturation = 1 - b / hsi.Intensity;
            }
            if (g > r && b >= r)
            {
                hsi.Intensity = (r + g + b) / 3;
                hsi.Hue = (b - r) / (3 * (hsi.Intensity - r) + 1);
                hsi.Saturation = 1 - r / hsi.Intensity;
            }
            if (r >= g && b > g)
            {
                hsi.Intensity = (r + g + b) / 3;
                hsi.Hue = (r - g) / (3 * (hsi.Intensity - g) + 2);
                hsi.Saturation = 1 - g / hsi.Intensity;
            }
            
            return hsi;
        }

        public static RGB HSI2RGB(this HSI hsi)
        {
            double r = 0, g = 0, b = 0;

            double h = hsi.Hue;
            double s = hsi.Saturation;
            double i = hsi.Intensity;

            if (h >= 0 && h < 1)
            {
                r = i * (1 + 2 * s - 3 * s * h);
                g = i * (1 - s + 3 * s * h);
                b = i * (1 - s);
            }
            if (h >= 1 && h < 2)
            {
                r = i * (1 - s);
                g = i * (1 + 5 * s - 3 * s * h);
                b = i * (1 - 4 * s + 3 * s * h);
            }
            if (h >= 2 && h <= 3)
            {
                r = i * (1 - 7 * s + 3 * s * h);
                g = i * (1 - s);
                b = i * (1 + 8 * s - 3 * s * h);
            }

            return new RGB((byte)r, (byte)g, (byte)b);
        }
    }
}
